package util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang.StringUtils;

/**
 * 日期工具类,用来处理日期格式化，日期转字符串，字符串转日期等操作。
 *
 */
public class DateUtil {
	/**
	 * 转会当前日期为字符串格式，返回格式为：yyyy-dd-MM
	 * @return
	 */
	
	public static String FORMAT11="yyyy-dd-MM"; 
	public static String FORMAT7="yyyy-dd";
	public static String currentDate2String(){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");
		return formatter.format(new Date());
	}
	
	/**
	 * 日期加天数,可以向前加，向后加
	 * 
	 * @param date
	 *             日期
	 * @param day
	 *             分钟
	 * @return 返回相加后的日期
	 */
	public static Date addDate(Date date, int millis) {

		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(getMillis(date) + ((long) millis)  * 60 * 1000);

		return c.getTime();
	}
	
	/**
	 * 日期加月数,可以向前加，向后加
	 * 
	 * @param date  日期
	 * @param addMonths   月
	 * @return 返回相加后的日期
	 */
	public static Date addMonth(Date date, int addMonths) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, addMonths);
		return calendar.getTime();
	}
	
	/**
	 * 日期加月数,可以向前加，向后加
	 * 
	 * @param date  日期
	 * @param addMonths   月
	 * @return 返回相加后的日期
	 */
	public static Date addYear(Date date, int addYear) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.YEAR, addYear);
		return calendar.getTime();
	}
	
	
	/**   
	 * 将字符串转换为日期   
	 *    
	 * @param str   
	 * @return   
	 * @throws ParseException 
	 */
	public static Date parseStringToDate(String str, String format) {

		DateFormat formatter = null;
		Date date = null;
		if (StringUtils.isNotEmpty(str)) {

			if (StringUtils.isBlank(format)) {
				formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			}
			else {
				formatter = new SimpleDateFormat(format);
			}
		}

		try {
			date = formatter.parse(str);
		}catch (Exception e) {
			formatter = new SimpleDateFormat("yyyy-MM-dd");
			try {
				date = formatter.parse(str);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}
		
		return date;
	}

	
	/**
	 * 日期转换为字符串
	 * 
	 * @param date 日期
	 * @param format 格式
	 * @return 返回字符型日期
	 */
	public static String parseDateToString(Date date, String format) {

		String result = "";
		DateFormat formatter = null;
		try {
			if (date != null) {
				if (StringUtils.isBlank(format)) {
					formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				}
				else {
					formatter = new SimpleDateFormat(format);
				}
				result = formatter.format(date);
			}
		}
		catch (Exception e) {
		}
		return result;
	}
	
	/**
	 * 返回日期代表的毫秒
	 * 
	 * @param date
	 *             日期
	 * @return 返回毫秒
	 */
	public static long getMillis(Date date) {

		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}

	public static void main(String[] args) {
		Date date=DateUtil.addMonth(new Date(), -1);
		
		System.out.println(DateUtil.parseDateToString(date, "yyyy-MM-dd"));
	}
	
	
	
	
	
	/**
	 * 将当前日期转换成yyyyMMddHHmmss的字符串. 如：20071012141350
	 * @return
	 */	
	public static String currDateToStr() {
		return dateToStr(new java.util.Date(), "yyyyMMddHHmmss");
	}
	
	
	/**
	 * 将日期转换成指定格式的字符串.
	 * @param date 日期
	 * @param dateFormat 日期格式. 如果为空，默认为:yyyy-MM-dd HH:mm:ss.
	 * @return
	 */	  
	public static String dateToStr(final Date date, String dateFormat) {
		if (date == null || "".equals(date)){
			//log.debug("未知时间");
			return ""; 
			//return "未知时间";
		}
		try{
			if(dateFormat == null || dateFormat.trim().length() ==0)
				dateFormat = "yyyy-MM-dd HH:mm:ss";
			DateFormat fmt = new SimpleDateFormat(dateFormat.trim());
			return fmt.format(date);
		}catch(Exception ex){
			return ""; 
	  	   //return "日期格式不匹配";	
		}
	}
	
	/**
	 * 将字符串转换成格式为：yyyy-MM-dd 日期.
	 * @param str
	 * @return
	 */
	public static Date strToDate(final String str) {
		if(str == null || str.trim().length() == 0)
			return null;
		try{ 
		  	DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		  	return fmt.parse(str.trim());
		  	
	  	}catch(Exception ex){
	  		return null;
	  	}
	 }
	
	/**
	 * 将字符串转换成格式为：yyyy-MM-dd 日期.
	 * @param str
	 * @return
	 */
	public static Date strToDate(final String str,String dateFormat) {
		if(str == null || str.trim().length() == 0)
			return null;
		try{ 
		  	DateFormat fmt = new SimpleDateFormat(dateFormat);
		  	return fmt.parse(str.trim());
		  	
	  	}catch(Exception ex){
	  		return null;
	  	}
	 }
	
	/**
	 * 转换格式
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate2String(java.util.Date date, String pattern){
		SimpleDateFormat formtter = new SimpleDateFormat();
		formtter.applyPattern(pattern);
		return formtter.format(date);
	}
	
	 /**给定两个时间相差的月数,String版**/
    public static int monthsBetween(String pFormerStr,String pLatterStr){
    	GregorianCalendar vFormer = (GregorianCalendar) GregorianCalendar.getInstance();
    	vFormer.setTime(DateUtil.parseStringToDate(pFormerStr, "yy-MM"));
    	GregorianCalendar vLatter = (GregorianCalendar) GregorianCalendar.getInstance();
    	vLatter.setTime(DateUtil.parseStringToDate(pLatterStr, "yy-MM"));
        return monthsBetween(vFormer,vLatter);
    }
	
	@SuppressWarnings("static-access")
	public static int monthsBetween(GregorianCalendar pFormer,GregorianCalendar pLatter){
        GregorianCalendar vFormer = pFormer,vLatter = pLatter;
        boolean vPositive = true;
        if( pFormer.before(pLatter) ){
            vFormer = pFormer;
            vLatter = pLatter;
        }else{
            vFormer = pLatter;
            vLatter = pFormer;
            vPositive = false;
        }
 
        int vCounter = 0;
        while(vFormer.get(vFormer.YEAR) != vLatter.get(vLatter.YEAR) ||
             vFormer.get(vFormer.MONTH) != vLatter.get(vLatter.MONTH)){
            vFormer.add(Calendar.MONTH, 1);
            vCounter++;
        }
        if( vPositive)
            return vCounter;
        else
            return -vCounter;
    }
	
	public static long dayBetween(String time1, String time2){
		  long quot = 0;
		  SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
		  try {
		   Date date1 = ft.parse( time1 );
		   Date date2 = ft.parse( time2 );
		   quot = date2.getTime() - date1.getTime();
		   quot = quot / 1000 / 60 / 60 / 24;
		  } catch (ParseException e) {
		   e.printStackTrace();
		  }
		  return quot;
		 }
	public static Integer getYear(){
	  	DateFormat fmt = new SimpleDateFormat("yyyy");
	  	String year = fmt.format(new Date());
	  	return Integer.parseInt(year);
	}
	public static Integer getMonth(){
	  	DateFormat fmt = new SimpleDateFormat("MM");
	  	String month = fmt.format(new Date());
	  	return Integer.parseInt(month);
	}
	/**
	 * 当前日
	 * @return
	 */
	public static Integer getDay(){
		Date aDate = new Date(System.currentTimeMillis()); 
		Calendar calendar = GregorianCalendar.getInstance(); 
		calendar.setTime(aDate);
	  	return calendar.get(Calendar.DAY_OF_MONTH);
	}
	/**
	 * 当前小时24小时制
	 * @return
	 */
	public static Integer getHour24(){
		Date aDate = new Date(System.currentTimeMillis()); 
		Calendar calendar = GregorianCalendar.getInstance(); 
		calendar.setTime(aDate);
	  	return calendar.get(Calendar.HOUR_OF_DAY);
	}
	/**
	 * 当前小时12小时制
	 * @return 
	 */
	public static Integer getHour12(){
		Date aDate = new Date(System.currentTimeMillis()); 
		Calendar calendar = GregorianCalendar.getInstance(); 
		calendar.setTime(aDate);
	  	return calendar.get(Calendar.HOUR);
	}
	/**
	 * 当前分
	 * @return
	 */
	public static Integer getMinute(){
		Date aDate = new Date(System.currentTimeMillis()); 
		Calendar calendar = GregorianCalendar.getInstance(); 
		calendar.setTime(aDate);
	  	return calendar.get(Calendar.MINUTE);
	}
	
	
	/**
	 * 获取当前时间的上个月，格式：yyyy-MM
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static String getLastMonth(){
		java.util.Calendar   c   =   java.util.Calendar.getInstance();   
		c.add(c.MONTH,-1);//得到上个月的月份   
	  	DateFormat fmt = new SimpleDateFormat("yyyy-MM");
	  	String month = fmt.format(c.getTime());
	  	return month;
	}
}
